
import json
from venv import logger

#from celery.utils.time import timezone
from django.conf import settings
from django.http import JsonResponse, HttpResponseForbidden
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.utils.datetime_safe import datetime
from django.views import View

from homes.models import House

from orders.models import Order

from ihome.utils.mixins import LoginRequiredJSONMixin


class Orders(View, LoginRequiredJSONMixin):
    """获取订单列表的添加订单"""

    """获取订单列表"""

    def get(self, request):
        # 接收参数
        user = request.user
        role = request.GET.get('role')

        # 校验参数
        if not role:
            return JsonResponse({"errno": 400, "errmsg": "参数错误"})

        if role not in ["landlord", "custom"]:
            return JsonResponse({"errno": 400, "errmsg": "参数错误"})

        if role == "custom":
            # 查询当前自己下了哪些订单
            orders = Order.objects.filter(user=user).order_by("-create_time")


        else:
            # 查询自己房屋都有哪些订单
            houses = House.objects.filter(user=user)
            house_ids = [house.id for house in houses]
            orders = Order.objects.filter(house_id__in=house_ids).order_by("-create_time")
        orders_dict = []
        for order in orders:

            orders_dict.append({
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": settings.QINIU_URL + order.house.index_image_url,
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": Order.ORDER_STATUS_ENUM[order.status],
                "title": order.house.title
            })

        return JsonResponse({"errno": 0, "errmsg": "发布成功", "data": {"orders": orders_dict}})

    def post(self, request):
        # 接收参数
        user = request.user
        json_dict = json.loads(request.body)
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')

        # 校验参数
        # 校验全部参数
        if not all([house_id, start_date, end_date]):
            return HttpResponseForbidden('缺少必传参数')

        # 校验参数house_id
        try:
            house = House.objects.get(id=house_id)
        except House.DoesNotExist:
            return JsonResponse({'errno': 4100, 'errmsg': '参数house_id错误'})

        try:
            # 转化为日期格式
            start_date = datetime.strptime(start_date, '%Y-%m-%d')
            end_date = datetime.strptime(end_date, '%Y-%m-%d')
            assert start_date < end_date, Exception('开始日期大于结束日期')
            # 总天数
            days = (end_date - start_date).days
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4100, 'errmsg': '参数错误'})

        # 验证是否自己的房子
        if user.id == house.user.id:
            # 说明当前用户是房东
            return JsonResponse({'errno': 4100, 'errmsg': '不能预定自己的房子'})

        # 判断用户下单的时间段是否有别的订单
        try:
            count = Order.objects.filter(house_id=house_id,
                                         begin_date__lte=end_date,
                                         end_date__gte=start_date).count()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4100, 'errmsg': '查询数据库出错'})
        if count > 0:
            # 说明房子被别人预定
            return JsonResponse({'errno': 4100, 'errmsg': '房子已被预定'})

        # 计算总价
        amount = days * house.price
        try:
            order = Order.objects.create(
                house_id=house_id,
                user_id=user.id,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                amount=amount,
                house_price=house.price
                )
        except Order.DoesNotExist:
            return JsonResponse({'errno': 4100, 'errmsg': '保存数据失败'})
        # 组织要相应的数据
        data = {'order_id': order.id}
        # 响应提交订单结果
        return JsonResponse({"data": data, "errno": 0, "errmsg": "下单成功"})

    def put(self, request, order_id):
        """接单和拒单"""
        # 接收参数
        user = request.user
        json_dict = json.loads(request.body)
        action = json_dict.get('action')

        # 校验参数
        if action not in ('accept', 'reject'):
            return JsonResponse({'errno': 400, 'errmsg': '参数有误'})

        # 通过订单id查询订单模型
        try:
            order = Order.objects.filter(id=order_id, status=Order.ORDER_STATUS["WAIT_ACCEPT"]).first()
            house = order.house
        except Exception as e:
            logger.error(e)
            return JsonResponse({"errno": 400, "errmsg": "查询数据失败"})

        # 判断当前订单是否存在
        if not order or house.user != user:
            return JsonResponse({"errno": 400, "errmsg": "数据出错"})
        # 判断是否接单
        if action == 'accept':
            order.status = Order.ORDER_STATUS["WAIT_COMMENT"]
        elif action == 'reject':
            reason = json_dict.get('reason')
            if not reason:
                return JsonResponse({'errno': 400, 'errmsg': '没有原因'})

            # 设置拒单状态为拒单 并且添加拒单原因
            order.status = Order.ORDER_STATUS["REJECTED"]
            order.comment = reason

        # 实现数据库保存
        try:
            order.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 400, 'errmsg': '保存数据库失败'})

        return JsonResponse({'errno': 0, 'errmsg': '操作成功'})